<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<title>离线模式</title>
		<!-- css代码 start -->
		<link href="../../css/mui.min.css" rel="stylesheet" />
		<link href="../../css/global.css" rel="stylesheet" />
		<link href="../../css/style.css" rel="stylesheet" />
		<link href="../../css/checkbox.css" rel="stylesheet" />
		<link href="../../css/task.css" rel="stylesheet" />
		<style>
			.mui-checkbox input[type=checkbox], .mui-radio input[type=radio]{
				top: 8px;
				right: -10px;
			}
			#div {
				width: 0px;
				height: 0px;
				background: red;
				position: fixed;
				top: 65%;
				left: 50%;
			}
			#div1 {
				width: 0px;
				height: 0px;
				background: red;
				position: fixed;
				top: 70%;
				left: 50%;
			}
			/*移除底部或顶部三角,需要在删除此代码*/
			.mui-popover .mui-popover-arrow:after {
				width: 0px;
			}
			.item_box .type p input {
				width: 60%;
				margin-bottom: 10px;
				margin-right: 10px;
			}
			.item_box .type p .collateBtn {
				padding: 10px;
				background: #ea1e1a;
				border-radius: 10px;
				color: #FFFFFF;
			}
			.item_box .btm{
				display: flex;
				justify-content: space-between;
				width: 90%;
				margin: 0 auto;
			}
			.item_box .btm li span.i_3{
				background-size: 20px 16px;
			}
			.item_box .btm li span.i_4{
				background-size: 20px 16px;
			}
			.item_box .btm li span.i_5{
				background-size: 20px 16px;
			}
			.item_box .btm li{
				text-align: inherit;
			}
			.item_box .btm li span{
				padding-left: 21px;
				font-size: 14px;
				color: #2188b9;
			}
			.item_box .item .name {
			    padding: 5px 17px;
			    height: auto;
			    line-height: 20px;
			}
		</style>
		<!-- css代码 end -->
	</head>
	<body>
		<div id="div"></div>
		<div id="popover" class="mui-popover shadow popover">
			<p class="title">请确定服务是否全部完成?</p>
			<div class="btn_box">
				<span class="fl" id="noTrue">未完成</span>
				<span class="fr red" id="btnYes">已完成</span>
			</div>
		</div>
		
		<div id="div1"></div>
		<div id="popover1" class="mui-popover shadow popover">
			<div class="details_con">
				<div class="clum" style="margin: 0 10px;">
					<span class="name">预计上门时间<em class="t_red">*</em></span>
					<button id='estimatedVisitingTime' type="button" class="selectDate">请选择时间</button>
				</div>
				<div class="clum" style="margin: 0 10px;">
					<span class="name">预计工时<em class="t_red">*</em></span>
					<input id="estimatedWorkingHours" type="number" class="d_ipt" placeholder="请输入预计工时" onchange="jisuan('1')" />
				</div>
				<div class="clum" style="margin: 0 10px;">
					<span class="name">预计离开时间<em class="t_red">*</em></span>
					<input id="estimatedDepartureTime" type="text" class="d_ipt" placeholder="自动计算" disabled="disabled" />
				</div>
			</div>
			<div class="btn_box">
				<span class="fl" id="closeDoor">取消</span>
				<span class="fr red" id="saveDoor">确定</span>
			</div>
		</div>
		
		<div id="popover2" class="mui-popover shadow popover">
			<p class="title">请确认是否退出离线模式?</p>
			<div class="btn_box">
				<span class="fl" onclick="closeDoor()">取消</span>
				<span class="fr red" onclick="outToOffline()">确定</span>
			</div>
		</div>

		<header class="mui-bar mui-bar-nav">
			<a id="outToOffline" class="mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 id="title" class="mui-title">离线模式</h1>
		</header>
		<div class="mui-content">
			<div class="item_box" id="item_box">
			
			</div>
		</div>
		<!-- js代码 start -->

		<!-- 基础js start -->
		<script src="../../js/mui.min.js"></script>
		<script src="../../js/utils/h.js"></script>
		<script src="../../js/constant.js"></script>
		<script src="../../js/common.js"></script>
		<script src="../../js/utils/base64.js"></script>
		<script src="../../js/utils/md5.js"></script>
		<script src="../../js/utils/sortMap.js"></script>
		<script src="../../js/utils/http.js"></script>
		<script src="../../js/app.js"></script>
		<script src="../../js/sqliteTools.js"></script>
		<!-- 基础js end -->
		<script src="../../js/utils/rolldate.min.js"></script>
		<script type="text/javascript" charset="utf-8">
			var offLineDatas = null;
			var dataId, dataIndex, signOffLon, signOffLat;

			function noData() {
				html = '<div class="nodata">—— 暂无数据 ——</div>';
				h("#item_box").html(html);
			}

			/**
			 * 初始化本地数据
			 */
			function initData() {
				var enginnerId = app.getUser().enginnerId;
				var sqliteTool = new sqliteTools();
				sqliteTool.openDatabase(function() {
					sqliteTool.selectService(enginnerId, function(flag, data) {
						offLineDatas = data
						if (!flag) {
							app.toast("查询失败")
							return;
						}

						if (!data || data.length == 0) {
							noData()
							return;
						}
						var str = '';
						mui.each(data, function(i, info) {
							str += '<div class="item">'
							str += '<div class="bar">'
							str += '<span class="number">' + info.serviceNo + '<img src="../../images/icon_204.png" /></span>'
							str += '</div>'
							str += '<div class="name">' + (JS.IsNullOrEmpty(info.customerName) ? "" : info.customerName) + '</div>'
							str += '<div class="type">'
							str += '<p>签到时间：<span>' + (JS.IsNullOrEmpty(info.signInTime) ? "尚未签到" : info.signInTime) +
								'</span><img src="../../images/icon_202.png" /></p>'
							if(info.serviceType == "安装" && info.subServiceType == "安装"){
								if (JS.IsNullOrEmpty(info.newInstSn)) {
									str += '<p>仪器序列号：<span>' + (JS.IsNullOrEmpty(info.instSn) ? "" : info.instSn) +
										'</span><img src="../../images/icon_104_cur.png" /></p>'
									str += '<p>核对结果：<span>尚未核对</span><img src="../../images/icon_104_cur.png" /></p>'
								} else {
									str += '<p>仪器序列号：<span>' + (JS.IsNullOrEmpty(info.newInstSn) ? "" : info.newInstSn) +
										'</span><img src="../../images/icon_104_cur.png" /></p>'
									if (info.instSn == info.newInstSn) {
										str += '<p>核对结果：<span>一致</span><img src="../../images/icon_104_cur.png" /></p>'
									} else {
										str += '<p>核对结果：<span>不一致</span><img src="../../images/icon_104_cur.png" /></p>'
									}
								}
							} else {
								str += '<p>仪器序列号：<span>' + (JS.IsNullOrEmpty(info.instSn) ? "" : info.instSn) +
									'</span><img src="../../images/icon_104_cur.png" /></p>'
							}						
							/* str += '<p>签离时间：<span>' + (JS.IsNullOrEmpty(info.signOffTime) ? "" : info.signOffTime) +
								'</span><img src="../../images/icon_202.png" /></p>', */
								str += '</div>'
							if(info.serviceType == "安装" && info.subServiceType == "安装"){	
								str += '<div class="type">'						
								str += '<p><input type="text" id="newInstSn' + i + '"/><span class="collateBtn" onclick="collateInstSn(\'' + i + '\', \'' +
									info.id + '\', \'' + info.instSn + '\', \'' + info.newInstSn + '\', \'' + info.signIn +
									'\')">核对序列号</span></p>'
								str += '</div>'
							}
							str += '<ul class="btm">'
							str += '<li><span class="i_3" onclick="signIn(\'' + i + '\', \'' + info.id + '\', \'' + info.signIn +
								'\')">签到</span></li>'
							/* str += '<li><span class="i_4" onclick="signOff(\'' + i + '\', \'' + info.id + '\', \'' + info.signIn +
								'\', \'' + info.signOff + '\')">签离</span></li>' */
							str += '<li><span class="i_3" onclick="workingLog(\'' + i + '\', \'' + info.id + '\', \'' + info.signIn +
								'\')">日志</span></li>'
							/* str += '<li><span class="i_5" onclick="uploadData(\'' + i + '\', \'' + info.id + '\', \'' + info.signIn +
								'\')">上传数据</span></li>' */
							str += '</ul>'
							str += '</div>'
						})
						h("#item_box").html(str)
					})
				})
			}

			/**
			 * 签到
			 * 
			 * @param {Object} index
			 * @param {Object} id
			 */
			function signIn(index, id, signIn) {
				if (signIn == '1') {
					app.toast("已签到")
					return
				}
				app.showWaiting("定位中...")
				plus.geolocation.getCurrentPosition(function(p) {
					app.closeWaiting()
					var signInTime = new Date().Format("yyyy-MM-dd HH:mm:ss");
					var signInLon = p.coords.longitude;
					var signInLat = p.coords.latitude;
					var sqliteTool = new sqliteTools();
					sqliteTool.openDatabase()
					sqliteTool.insertServiceSignInData(id, "1", signInTime, signInLon, signInLat, "1", function(flag) {
						if (!flag) {
							app.toast("请到空旷的地方操做")
							return;
						}
						app.toast("签到成功");
						sqliteTool.closeDB();
						initData();
					})
				}, function(e) {
					console.log('Geolocation error: ' + e.message);
					app.closeWaiting()
					app.toast("定位失败")
				},  {geocode: false});
			}

			/**
			 * 签离
			 * 
			 * @param {Object} index
			 * @param {Object} id
			 */
			/* function signOff(index, id, signIn, signOff) {
				if (signIn != '1') {
					app.toast("请先签到")
					return;
				}
				if (signOff == '1') {
					app.toast("已签离")
					return;
				}
				app.showWaiting("定位中...")
				plus.geolocation.getCurrentPosition(function(p) {
					app.closeWaiting()
					signOffLon = p.coords.longitude;
					signOffLat = p.coords.latitude;
					dataId = id;
					dataIndex = index;
					mui("#popover").popover('toggle', document.getElementById("div"));
				}, function(e) {
					console.log('Geolocation error: ' + e.message);
					app.closeWaiting()
					app.toast("请到空旷的地方操做")
				}, {geocode: false});
			} */

			/**
			 * 工作日志
			 * 
			 * @param {Object} index
			 * @param {Object} id
			 */
			function workingLog(index, id, signIn) {
				if (signIn != '1') {
					app.toast("请先签到")
					return;
				}
				var info = offLineDatas[index];
				app.jumpTo('logAdd.html', 'view/offline/logAdd.html', {
					data: info
				});
			}

			/**
			 * 核对序列号
			 * 
			 * @param {Object} index
			 * @param {Object} id
			 */
			function collateInstSn(index, id, instSn, newInstSn, signIn) {
				if (signIn != '1') {
					app.toast("请先签到")
					return;
				}
				var newInstSnInput = h('#newInstSn' + index).val();
				if (!newInstSnInput) {
					app.toast("请输入序列号")
					return;
				}
				var sqliteTool = new sqliteTools();
				sqliteTool.openDatabase()
				sqliteTool.insertServiceCollateData(id, newInstSnInput, function(flag) {
					if (!flag) {
						app.toast("核对失败")
						return;
					}
					app.toast("核对成功，且只会上传最新一次核对的数据")
					initData();
				})
			}

			/**
			 * 上传数据
			 * 
			 * @param {Object} index
			 * @param {Object} id
			 */
			/* function uploadData(index, id, signIn) {
				if (signIn != '1') {
					app.toast("请先签到")
					return;
				}
				var info = offLineDatas[index];
				app.showWaiting("数据上传中...")
				ajaxPost(BASE_URL + 'cc/offline/uploadOfflineData', info, function(data){
					app.closeWaiting()
					if (data.code === 200) {
						var sqliteTool = new sqliteTools();
						sqliteTool.openDatabase()
						sqliteTool.uploadServiceSuccessData(info.id, function() {
							initData();
						})
						app.toast("上传成功")
					} else {
						app.toast(data.msg)
					}
				}, function(errorMsg){
					app.closeWaiting()
					app.toast(errorMsg)
				});		
			} */

			// 取消方法 关闭弹窗
			function closeDoor() {
				mui("#popover").popover('hide', document.getElementById("div"));
				mui("#popover1").popover('hide', document.getElementById("div1"));
				mui("#popover2").popover('hide', document.getElementById("div"));
			}
			
			// 退出离线模式
			function outToOffline() {	
				closeDoor();
				var enginnerId = app.getUser().enginnerId;
				var sqliteTool = new sqliteTools();
				sqliteTool.openDatabase();
				sqliteTool.selectUploadService(enginnerId, function(flag, data) {
					if (!flag) {
						app.toast("操作失败");
						sqliteTool.closeDB();
						return;
					}
									
					if(data && data.length > 0){
						app.showWaiting("数据正在上传,请稍后...")
						ajaxPost(BASE_URL + 'cc/offline/uploadOfflineDataBatch', data, function(resData){						
							if (resData.code === 200) {
								for (var i = 0; i < data.length; i++) {
									sqliteTool.uploadServiceSuccessData(data[i].id, function(callBackflag, callId) {
										console.log("uploadId="+callId+"---"+callBackflag)
									})
								}
								
								setTimeout(function() {
									sqliteTool.closeDB();
									initData();
									app.closeWaiting();
									app.toast("上传成功");
									// 退出离线模式时设置离线状态为0
									h.setItem("offlineFlag", "0");
									
									var self = plus.webview.currentWebview();
									// 刷新TL首页
									var indexTl=plus.webview.getWebviewById('view/main/indexTL.html');
									if(indexTl){
										indexTl.evalJS('getMyTeamCount()')
									}
									
									// 1、刷新FSE首页
									var indexFSE = plus.webview.getWebviewById('view/main/indexFSE.html');
									if (indexFSE) {
										indexFSE.evalJS('getList("0")')
									}			
									mui.back();
									self.close();
								}, 200);					
							} else {
								sqliteTool.closeDB();
								app.closeWaiting();
								app.toast(resData.msg);
							}
						}, function(errorMsg){
							sqliteTool.closeDB();
							app.closeWaiting();
							app.toast(errorMsg);
						});
					} else {
						sqliteTool.closeDB();
						// 退出离线模式时设置离线状态为0
						h.setItem("offlineFlag", "0");
						
						var self = plus.webview.currentWebview();
						// 刷新TL首页
						var indexTl=plus.webview.getWebviewById('view/main/indexTL.html');
						if(indexTl){
							indexTl.evalJS('getMyTeamCount()')
						}
						
						// 1、刷新FSE首页
						var indexFSE = plus.webview.getWebviewById('view/main/indexFSE.html');
						if (indexFSE) {
							indexFSE.evalJS('getList("0")')
						}			
						mui.back();
						self.close();
					}
				})
			}

			// 自动计算方法
			function jisuan(date) {
				var estimatedVisitingTime;
				if (date != "1") {
					estimatedVisitingTime = date
				} else {
					estimatedVisitingTime = h("#estimatedVisitingTime").html();
				}
				if (estimatedVisitingTime == null || estimatedVisitingTime == "" || estimatedVisitingTime == "请选择时间") {
					return
				}
				var evt = stringYYYYMMDDHHMMToDate(estimatedVisitingTime).getTime();
				var estimatedWorkingHours = h("#estimatedWorkingHours").val();
				if (estimatedWorkingHours == null || estimatedWorkingHours == "") {
					return
				}
				var edt = evt + estimatedWorkingHours * 60 * 60 * 1000;
				var estimatedDepartureTime = new Date(edt).Format("yyyy-MM-dd HH:mm");
				h("#estimatedDepartureTime").val(estimatedDepartureTime);
			}

			(function($, doc) {
				$.init();

				$.plusReady(function() {

					new Rolldate({
						el: '#estimatedVisitingTime',
						format: 'YYYY-MM-DD hh:mm',
						beginYear: 2015,
						endYear: 2050,
						trigger: 'click',
						lang: {
							title: '请选择预计上门时间',
						},
						confirm: function(date) {
							jisuan(date)
						}
					})
					
					// 进入离线模式时设置离线状态为1
					h.setItem("offlineFlag", "1");

					initData();

					h("#btnYes").tap(function() {
						var signOffTime = new Date().Format("yyyy-MM-dd HH:mm");
						var sqliteTool = new sqliteTools();
						sqliteTool.openDatabase()
						sqliteTool.insertServiceSignOffData(dataId, "1", signOffTime, signOffLon, signOffLat, "", "", "", function(flag) {
							if (!flag) {
								app.toast("签离失败")
								return;
							}
							closeDoor();
							app.toast("签离成功")
							initData();
						})
					})

					h("#noTrue").tap(function() {
						$("#popover").popover('hide', document.getElementById("div"));
						$("#popover1").popover('toggle', document.getElementById("div1"));
					});

					h("#saveDoor").tap(function() {
						var estimatedVisitingTime = h('#estimatedVisitingTime').html()
						var estimatedWorkingHours = h('#estimatedWorkingHours').val()
						var estimatedDepartureTime = h('#estimatedDepartureTime').val()
						
						jisuan('1');
						if (estimatedVisitingTime == null || estimatedVisitingTime == "" || estimatedVisitingTime == "请选择时间") {
							app.closeWaiting()
							app.toast("请选择预计上门时间");
							return
						}
						if (estimatedWorkingHours == null || estimatedWorkingHours == "") {
							app.closeWaiting()
							app.toast("请输入预计工时");
							return
						}
						
						var evt = stringYYYYMMDDHHMMToDate(estimatedVisitingTime).getTime();
						var newDate = new Date().getTime();
						if(evt <= newDate){
							app.closeWaiting()
							app.toast("预计上门时间不可以小于当前时间");
							return
						}
						
						var signOffTime = new Date().Format("yyyy-MM-dd HH:mm");
						var sqliteTool = new sqliteTools();
						sqliteTool.openDatabase()
						sqliteTool.insertServiceSignOffData(dataId, "1", signOffTime, signOffLon, signOffLat, estimatedVisitingTime,
							estimatedWorkingHours, estimatedDepartureTime,function(flag) {
								if (!flag) {
									app.toast("签离失败")
									return;
								}
								closeDoor();
								app.toast("签离成功")
								initData();
							})
					})

					h("#closeDoor").tap(function() {
						closeDoor();
					})

					h("#outToOffline").tap(function() {
						mui("#popover2").popover('toggle', document.getElementById("div"));
					})
				});
			}(mui, document));
		</script>
		<!-- js代码 end -->
	</body>
</html>